package com.joysuch.wwyt.common.service.impl;

import cn.zlg.common.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.common.service.PersonalizeDesignService;
import com.joysuch.wwyt.core.bean.AuthorityBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseLoginAccount;
import com.joysuch.wwyt.core.entity.BaseMenuFunction;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseLoginAccountDao;
import com.joysuch.wwyt.core.repository.BaseMenuFunctionDao;
import com.joysuch.wwyt.core.service.AuthorityService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.licence.service.LicenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author ZhangDong
 * @Date 2020/6/11 16:47
 */
@Service
@Slf4j
public class PersonalizeDesignServiceImpl implements PersonalizeDesignService {

    @Autowired
    private BaseLoginAccountDao baseLoginAccountDao;
    @Autowired
    private BaseMenuFunctionDao baseMenuFunctionDao;
    @Autowired
    private AuthorityService authorityService;
    @Autowired
    private LicenceService licenceService;

    @Override
    @Transactional
    public ResultBean personalMenuSave(List<Long> menuIds) {
        BaseUser baseUser = new BaseUser();
        baseUser.setId(Context.getCurrentUserId());
        BaseLoginAccount baseLoginAccount = baseLoginAccountDao.findByBaseUser(baseUser);
        menuIds = menuIds == null ? Lists.newArrayList() : menuIds;
        baseLoginAccount.setMenuIdJson(JSON.toJSONString(menuIds));
        baseLoginAccountDao.save(baseLoginAccount);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public ResultBean personalMenuList() {
        BaseUser baseUser = new BaseUser();
        baseUser.setId(Context.getCurrentUserId());
        BaseLoginAccount baseLoginAccount = baseLoginAccountDao.findByBaseUser(baseUser);
        String menuIdJson = baseLoginAccount.getMenuIdJson();
        List<Long> longs;
        if (menuIdJson == null || CollectionUtils.isEmpty((longs = JSON.parseArray(menuIdJson, Long.class)))) {
            return ResultBean.success(null);
        }
        List<BaseMenuFunction> baseMenuFunctionList = baseMenuFunctionDao.findAllById(longs);
        licenceService.filter(baseMenuFunctionList);

        List<AuthorityBean> temp = authorityService.parse(baseMenuFunctionList);
        return ResultBean.wrapSuccessfulResult(authorityService.convertMenuData(temp));
    }

}
